# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Check gvn:* revprops.

- Block gvn:approve*
- Block gvn:submitted
- Sanity check gvn:change
"""


import gvn.util


def RunHook(hi, logger):
  """Implements gvn.hooks.runner's RunHook interface

  Returns:
    -1: pass and bypass other hooks
    0: pass
    1: fail
    "string": fail and print string to the user
  """
  for (name, value) in hi.txn_props.iteritems():
    if name.startswith("gvn:approve"):
      return "gvn:approve* not allowed at commit time"

    if name == "gvn:submitted":
      return "gvn:submitted not allowed at commit time"

    if name == "gvn:change":
      if value is not None:
        (user_name, change_name,
         revision) = gvn.util.ParseChangeName(value)
        if None in [user_name, change_name, revision]:
          return "Invalid gvn:change value %s" % (value,)
        if user_name != hi.author:
          return ("%s not allowed to submit %s's change (%s)"
                  % (hi.author, user_name, value))
        # TODO(epg): Check that the changebranch actually exists;
        # checking for a delete of it in this txn should cover that.
        if not 1 <= revision <= hi.head:
          return ("Invalid revision number for gvn:change %d (%s)"
                  % (revision, value))

  return 0
